/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreateChangeFlightView.java
 *
 * Created on 26-jan-2010, 14:30:08
 */
package View;

import Controller.Controller;
import Model.Airport;
import Model.Flight;
import Model.Staff;
import Model.Plane;
import Model.AirMarshall;
import Util.StringToHtmlConverter;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;

/**
 *
 * @author Jeroen
 */
public class CreateChangeFlightView extends javax.swing.JInternalFrame implements KeyListener {

    private enum FieldEditing {

        PILOT, COPILOT, FROM, DESTINATION, PLANE, AIRMARSHALL
    }
    private FieldEditing currentField = null;
    private Flight flight = null;
    private boolean newFlight;

    /**
     * Creates new form CreateChangeFlightView
     */
    public CreateChangeFlightView(Flight flight) {
        initComponents();
        this.setTitle("Add Flight");
        if (flight != null) {
            this.setTitle("Change Flight");
            this.flight = flight;
            txtNumber.setText("" + flight.getNumber());
            SimpleDateFormat sdf = new SimpleDateFormat(Flight.FLIGHTDATAFORMAT);
            String sdate = sdf.format(flight.getDate());
            txtDate.setText(sdate);
            txtCopilot.setText(flight.getCopilot().toString());
            txtPilot.setText(flight.getPilot().toString());
            txtDestination.setText(flight.getDestination().toString());
            txtFrom.setText(flight.getFrom().toString());
            txtPlane.setText(flight.getPlane().toString());
            txtPersonal.setText(flight.getOtherPersonal().toString());
            txtStops.setText(flight.getStops().toString());
            if(flight.getMarshall()!=null){
            txtAirMarshall.setText(flight.getMarshall().toString());
            }
            this.newFlight = false;
        } else {
            this.flight = new Flight();
            this.newFlight = true;
            //Defaulting date to current date.
            DateFormat df = new SimpleDateFormat(Flight.FLIGHTDATAFORMAT);
            txtDate.setText(df.format(new Date()));
            this.flight.setDate(new Date());
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    private void searchPilot() {
        String searchString = txtPilot.getText();
        listSearchResults.setListData(Controller.Instance().searchStaffPilots(searchString).toArray());
    }

    private void searchCoPilot() {
        String searchString = txtCopilot.getText();
        listSearchResults.setListData(Controller.Instance().searchStaffPilots(searchString).toArray());

    }

    private void searchFrom() {
        String searchString = txtFrom.getText();
        listSearchResults.setListData(Controller.Instance().searchAirport(searchString, false).toArray());
    }

    private void searchDestination() {
        String searchString = txtDestination.getText();
        listSearchResults.setListData(Controller.Instance().searchAirport(searchString, false).toArray());
    }
//    
//     private void searchAirmarshall() {
//        String searchString = txtPilot.getText();
//        listSearchResults.setListData(Controller.Instance().setMarshall(searchString).toArray());
//    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblFlightNumber = new javax.swing.JLabel();
        lblPilot = new javax.swing.JLabel();
        lblCopilot = new javax.swing.JLabel();
        lblFrom = new javax.swing.JLabel();
        lblDestination = new javax.swing.JLabel();
        lblPlane = new javax.swing.JLabel();
        lblOthers = new javax.swing.JLabel();
        txtNumber = new javax.swing.JTextField();
        txtPilot = new javax.swing.JTextField();
        txtCopilot = new javax.swing.JTextField();
        txtFrom = new javax.swing.JTextField();
        txtDestination = new javax.swing.JTextField();
        txtPlane = new javax.swing.JTextField();
        btnSave = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listSearchResults = new javax.swing.JList();
        txtDate = new javax.swing.JTextField();
        lblDate = new javax.swing.JLabel();
        lblError = new javax.swing.JLabel();
        txtPersonal = new javax.swing.JTextField();
        txtStops = new javax.swing.JTextField();
        lblStops = new javax.swing.JLabel();
        lblAir = new javax.swing.JLabel();
        txtAirMarshall = new javax.swing.JTextField();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(flyaway.FlyAWayApp.class).getContext().getResourceMap(CreateChangeFlightView.class);
        lblFlightNumber.setText(resourceMap.getString("lblFlightNumber.text")); // NOI18N
        lblFlightNumber.setName("lblFlightNumber"); // NOI18N

        lblPilot.setText(resourceMap.getString("lblPilot.text")); // NOI18N
        lblPilot.setName("lblPilot"); // NOI18N

        lblCopilot.setText(resourceMap.getString("lblCopilot.text")); // NOI18N
        lblCopilot.setName("lblCopilot"); // NOI18N

        lblFrom.setText(resourceMap.getString("lblFrom.text")); // NOI18N
        lblFrom.setName("lblFrom"); // NOI18N

        lblDestination.setText(resourceMap.getString("lblDestination.text")); // NOI18N
        lblDestination.setName("lblDestination"); // NOI18N

        lblPlane.setText(resourceMap.getString("lblPlane.text")); // NOI18N
        lblPlane.setName("lblPlane"); // NOI18N

        lblOthers.setText(resourceMap.getString("lblOthers.text")); // NOI18N
        lblOthers.setName("lblOthers"); // NOI18N

        txtNumber.setText(resourceMap.getString("txtNumber.text")); // NOI18N
        txtNumber.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtNumber.setName("txtNumber"); // NOI18N

        txtPilot.setEditable(false);
        txtPilot.setText(resourceMap.getString("txtPilot.text")); // NOI18N
        txtPilot.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtPilot.setMinimumSize(new java.awt.Dimension(20, 6));
        txtPilot.setName("txtPilot"); // NOI18N
        txtPilot.addKeyListener(this);
        txtPilot.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPilotFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPilotFocusLost(evt);
            }
        });

        txtCopilot.setEditable(false);
        txtCopilot.setBackground(resourceMap.getColor("txtCopilot.background")); // NOI18N
        txtCopilot.setText(resourceMap.getString("txtCopilot.text")); // NOI18N
        txtCopilot.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("txtCopilot.border.lineColor"))); // NOI18N
        txtCopilot.setName("txtCopilot"); // NOI18N
        txtCopilot.addKeyListener(this);
        txtCopilot.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCopilotActionPerformed(evt);
            }
        });
        txtCopilot.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtCopilotFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCopilotFocusLost(evt);
            }
        });

        txtFrom.setEditable(false);
        txtFrom.setText(resourceMap.getString("txtFrom.text")); // NOI18N
        txtFrom.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("txtFrom.border.lineColor"))); // NOI18N
        txtFrom.setName("txtFrom"); // NOI18N
        txtFrom.addKeyListener(this);
        txtFrom.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtFromFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtFromFocusLost(evt);
            }
        });

        txtDestination.setEditable(false);
        txtDestination.setText(resourceMap.getString("txtDestination.text")); // NOI18N
        txtDestination.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtDestination.setName("txtDestination"); // NOI18N
        txtDestination.addKeyListener(this);
        txtDestination.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtDestinationFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDestinationFocusLost(evt);
            }
        });

        txtPlane.setEditable(false);
        txtPlane.setText(resourceMap.getString("txtPlane.text")); // NOI18N
        txtPlane.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtPlane.setName("txtPlane"); // NOI18N
        txtPlane.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPlaneFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPlaneFocusLost(evt);
            }
        });

        btnSave.setText(resourceMap.getString("btnSave.text")); // NOI18N
        btnSave.setName("btnSave"); // NOI18N
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnCancel.setText(resourceMap.getString("btnCancel.text")); // NOI18N
        btnCancel.setName("btnCancel"); // NOI18N
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        listSearchResults.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listSearchResults.setEnabled(false);
        listSearchResults.setName("listSearchResults"); // NOI18N
        listSearchResults.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listSearchResultsValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listSearchResults);

        txtDate.setText(resourceMap.getString("txtDate.text")); // NOI18N
        txtDate.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtDate.setName("txtDate"); // NOI18N
        txtDate.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDateFocusLost(evt);
            }
        });

        lblDate.setText(resourceMap.getString("lblDate.text")); // NOI18N
        lblDate.setName("lblDate"); // NOI18N

        lblError.setText(resourceMap.getString("lblError.text")); // NOI18N
        lblError.setName("lblError"); // NOI18N

        txtPersonal.setEditable(false);
        txtPersonal.setText(resourceMap.getString("txtPersonal.text")); // NOI18N
        txtPersonal.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtPersonal.setName("txtPersonal"); // NOI18N
        txtPersonal.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPersonalMouseClicked(evt);
            }
        });

        txtStops.setEditable(false);
        txtStops.setText(resourceMap.getString("txtStops.text")); // NOI18N
        txtStops.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtStops.setName("txtStops"); // NOI18N
        txtStops.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtStopsMouseClicked(evt);
            }
        });

        lblStops.setText(resourceMap.getString("lblStops.text")); // NOI18N
        lblStops.setName("lblStops"); // NOI18N

        lblAir.setText(resourceMap.getString("lblAir.text")); // NOI18N
        lblAir.setName("lblAir"); // NOI18N

        txtAirMarshall.setEditable(false);
        txtAirMarshall.setBorder(javax.swing.BorderFactory.createLineBorder(null));
        txtAirMarshall.setName("txtAirMarshall"); // NOI18N
        txtAirMarshall.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtAirMarshallMouseClicked(evt);
            }
        });
        txtAirMarshall.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtAirMarshallActionPerformed(evt);
            }
        });
        txtAirMarshall.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtAirMarshallFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtAirMarshallFocusLost(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblError, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(lblDestination)
                                .addComponent(lblFrom)
                                .addComponent(lblCopilot)
                                .addComponent(lblFlightNumber)
                                .addComponent(lblDate)
                                .addComponent(lblPilot)
                                .addComponent(lblStops)
                                .addComponent(lblPlane)
                                .addComponent(lblOthers))
                            .addComponent(lblAir))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtAirMarshall, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNumber, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtPilot, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCopilot, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtPlane, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtPersonal, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtFrom, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDestination, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtStops, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblFlightNumber))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblDate))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtPilot, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblPilot))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblCopilot)
                            .addComponent(txtCopilot, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblFrom)
                            .addComponent(txtFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDestination)
                            .addComponent(txtDestination, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtStops, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblStops))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtPlane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblPlane))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblOthers)
                            .addComponent(txtPersonal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblAir)
                            .addComponent(txtAirMarshall, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnCancel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblError, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtDateFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDateFocusLost
        try {
            txtDate.setBackground(Color.WHITE);
            DateFormat d = new SimpleDateFormat(Flight.FLIGHTDATAFORMAT);
            this.flight.setDate(d.parse(txtDate.getText()));
        } catch (ParseException ex) {
            Logger.getLogger(CreateChangeFlightView.class.getName()).log(Level.SEVERE, null, ex);
            txtDate.setBackground(Color.RED);
        }
    }//GEN-LAST:event_txtDateFocusLost

    private void txtPlaneFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlaneFocusGained
        txtPlane.setBorder(BorderFactory.createLineBorder(Color.orange));
        currentField = FieldEditing.PLANE;
        listSearchResults.setEnabled(true);
        listSearchResults.setListData(Controller.Instance().searchPlanesAvailable(this.flight.getDate()).toArray());
    }//GEN-LAST:event_txtPlaneFocusGained

    private void listSearchResultsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listSearchResultsValueChanged
        switch (currentField) {
            case PLANE:
                Plane tmpPlane = (Plane) listSearchResults.getSelectedValue();
                if (tmpPlane != null) {
                    this.flight.setPlane(tmpPlane);
                    txtPlane.setText(this.flight.getPlane().toString());
                }
                break;
            case PILOT:
                Staff tmpPilot = (Staff) listSearchResults.getSelectedValue();
                if (tmpPilot != null) {
                    this.flight.setPilot(tmpPilot);
                    txtPilot.setText(this.flight.getPilot().toString());
                }
                break;
            case COPILOT:
                Staff tmpCoPilot = (Staff) listSearchResults.getSelectedValue();
                if (tmpCoPilot != null) {
                    this.flight.setCopilot(tmpCoPilot);
                    txtCopilot.setText(this.flight.getCopilot().toString());
                }
                break;
            case FROM:
                Airport tmpFrom = (Airport) listSearchResults.getSelectedValue();
                if (tmpFrom != null) {
                    this.flight.setFrom(tmpFrom);
                    txtFrom.setText(this.flight.getFrom().toString());
                }
                break;
            case DESTINATION:
                Airport tmpDestination = (Airport) listSearchResults.getSelectedValue();
                if (tmpDestination != null) {
                    this.flight.setDestination(tmpDestination);
                    txtDestination.setText(flight.getDestination().toString());
                }
                break;
                case AIRMARSHALL:
                AirMarshall tmpAirmarshall = (AirMarshall) listSearchResults.getSelectedValue();
                if (tmpAirmarshall != null) {
                    this.flight.setMarshall(tmpAirmarshall);
                    txtAirMarshall.setText(this.flight.getMarshall().toString());
                }
        }
    }//GEN-LAST:event_listSearchResultsValueChanged
    private boolean saveFlight() {
        Integer flightNumber = null;
        ArrayList<String> errorMessages = new ArrayList<>();

        if (txtNumber.getText() == null) {
            errorMessages.add("Please fill in a flight number");
        } else {
            try {
                flightNumber = Integer.parseInt(txtNumber.getText());
            } catch (NumberFormatException e) {
                errorMessages.add("Flight number is not a number");
            }
        }
        if(flightNumber <0){
            errorMessages.add("Flight number must be a positive value");
        }

        if (flight.getPilot() == null) {
            errorMessages.add("Please select a pilot");
        }
        if (flight.getCopilot() == null) {
            errorMessages.add("Please select a copilot \n");
        }
        if (flight.getFrom() == null) {
            errorMessages.add("Please insert a correct Airfield: From field");
        }
        if (flight.getDestination() == null) {
            errorMessages.add("Please insert a correct Airfield: Destination Field");
        }
        if (flight.getPlane() == null) {
            errorMessages.add("Please insert a correct Plane");
        }
        if (flight.getPilot() != null && flight.getCopilot() != null && flight.getPilot() == flight.getCopilot()) {
            errorMessages.add("Pilot and CoPilot can't be the same");
        }
        if (flight.getDestination() != null && flight.getFrom() != null && flight.getDestination() == flight.getFrom()) {
            errorMessages.add("Destination and From airfield can't be the same");
        }
        if (flight.getOtherPersonal().contains(flight.getPilot()) || flight.getOtherPersonal().contains(flight.getCopilot())) {
            errorMessages.add("A pilot or copilot cannot also be registered as oher personal");
        }
        if (flight.getStops().contains(flight.getFrom()) || flight.getStops().contains(flight.getDestination())) {
            errorMessages.add("An airport cannot be booked as a stop if it is also the origin or the destination");
        }


        if (newFlight) {
            Calendar cal = Calendar.getInstance(Locale.FRANCE);
            Date today = new Date(cal.get(Calendar.YEAR) - 1900, cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
            if (flight.getDate().before(today)) {
                errorMessages.add("A flight cannot be booked in the past");
            }
        }

        if (!errorMessages.isEmpty()) {
            lblError.setText(StringToHtmlConverter.format(errorMessages));
            return false;
        }

        int amountnotprimary = 0;
        int amountagreed = 0;
        
        if(flight.getPilot().getPrimaryAirport() != null){
            if(flight.getFrom().getId() != flight.getPilot().getPrimaryAirport().getId()){
                amountnotprimary ++;
                if(JOptionPane.showConfirmDialog(this , "De Pilot: " + flight.getPilot().getName() + " verterkt niet van zijn/haar eigen airport weet u het zeker?") == JOptionPane.YES_OPTION){
                    amountagreed ++;
                }
            }
        }
        
        if(flight.getCopilot().getPrimaryAirport() != null){
            if(flight.getFrom().getId() != flight.getCopilot().getPrimaryAirport().getId()){
                amountnotprimary ++;
                if(JOptionPane.showConfirmDialog(this , "De CoPilot member: " + flight.getCopilot().getName() + " verterkt niet van zijn/haar eigen airport weet u het zeker?") == JOptionPane.YES_OPTION){
                    amountagreed ++;
                }
            }
        }
        
        for (Staff staff : flight.getOtherPersonal()) {
            if(staff.getPrimaryAirport() != null){
                if(flight.getFrom().getId() != staff.getPrimaryAirport().getId()){
                    amountnotprimary ++;
                    if(JOptionPane.showConfirmDialog(this , "De Staff member: " + staff.getName() + " verterkt niet van zijn/haar eigen airport weet u het zeker?") == JOptionPane.YES_OPTION){
                        amountagreed ++;
                    }
                }
            }
        }
     
        
        if(amountagreed == amountnotprimary){
        
            if (newFlight) {
                flight.setNumber(flightNumber);

                if (Controller.Instance().addFlight(flight)) {
                    JOptionPane.showMessageDialog(this, "Flight added");
                    return true;
                } else {
                    JOptionPane.showMessageDialog(this, "Unable to add flight");
                }
            } else {
                this.flight.setNumber(flightNumber);

                if (Controller.Instance().update(flight)) {
                    JOptionPane.showMessageDialog(this, "Flight saved");
                    return true;
                } else {
                    JOptionPane.showMessageDialog(this, "Unable to save flight");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "Unable to save flight");
        }
        return false;
    }

    private void txtPlaneFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlaneFocusLost
        txtPlane.setBorder(BorderFactory.createLineBorder(Color.lightGray));
        listSearchResults.setEnabled(false);
    }//GEN-LAST:event_txtPlaneFocusLost

    private void txtPilotFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPilotFocusLost
        txtPilot.setBorder(BorderFactory.createLineBorder(Color.lightGray));
        listSearchResults.setEnabled(false);
    }//GEN-LAST:event_txtPilotFocusLost

    private void txtCopilotFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCopilotFocusLost
        txtCopilot.setBorder(BorderFactory.createLineBorder(Color.lightGray));
        listSearchResults.setEnabled(false);
    }//GEN-LAST:event_txtCopilotFocusLost

    private void txtFromFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFromFocusLost
        txtFrom.setBorder(BorderFactory.createLineBorder(Color.lightGray));
        listSearchResults.setEnabled(false);
    }//GEN-LAST:event_txtFromFocusLost

    private void txtDestinationFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDestinationFocusLost
        txtDestination.setBorder(BorderFactory.createLineBorder(Color.lightGray));
        listSearchResults.setEnabled(false);
    }//GEN-LAST:event_txtDestinationFocusLost

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if(this.saveFlight()){
            this.dispose();
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void txtPersonalMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtPersonalMouseClicked
        ArrayList<Staff> stewarts = Controller.Instance().searchStaffStewardessAvailable(this.flight.getDate());
        final ChildPicker<Staff> staff = new ChildPicker<>(stewarts, new ArrayList<>(this.flight.getOtherPersonal()));

        staff.setVisible(true);
        staff.getOKButton().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (staff.getSelectedObjects().size() > 5) {
                    JOptionPane.showMessageDialog(null, "Er kunnen maximaal 5 stewardessen op een vlucht worden gezet", "Teveel personeel op een vlucht", JOptionPane.ERROR_MESSAGE);
                } else {
                    ChangePersonal(staff.getSelectedObjects());
                    staff.dispose();
                }
            }
        });
    }//GEN-LAST:event_txtPersonalMouseClicked

    private void txtStopsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtStopsMouseClicked
        final ChildPicker<Airport> stopAirports = new ChildPicker<>(Controller.Instance().getAirports(), new ArrayList<>(flight.getStops()));

        stopAirports.setVisible(true);
        stopAirports.getOKButton().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ChangeStops(stopAirports.getSelectedObjects());
                stopAirports.dispose();
            }
        });
    }//GEN-LAST:event_txtStopsMouseClicked

    private void txtPilotFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPilotFocusGained
        txtPilot.setBorder(BorderFactory.createLineBorder(Color.orange));
        currentField = FieldEditing.PILOT;
        listSearchResults.setEnabled(true);
        listSearchResults.setListData(Controller.Instance().searchStaffPilotsAvailable(this.flight.getDate()).toArray());        // TODO add your handling code here:
    }//GEN-LAST:event_txtPilotFocusGained

    private void txtCopilotFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCopilotFocusGained
        txtCopilot.setBorder(BorderFactory.createLineBorder(Color.orange));
        currentField = FieldEditing.COPILOT;
        listSearchResults.setEnabled(true);
        listSearchResults.setListData(Controller.Instance().searchStaffPilotsAvailable(this.flight.getDate()).toArray());        // TODO add your handling code here:
    }//GEN-LAST:event_txtCopilotFocusGained

    private void txtFromFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFromFocusGained
        txtFrom.setBorder(BorderFactory.createLineBorder(Color.orange));
        currentField = FieldEditing.FROM;
        listSearchResults.setEnabled(true);
        listSearchResults.setListData(Controller.Instance().getAirports().toArray());
    }//GEN-LAST:event_txtFromFocusGained

    private void txtDestinationFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDestinationFocusGained
        txtDestination.setBorder(BorderFactory.createLineBorder(Color.orange));
        currentField = FieldEditing.DESTINATION;
        listSearchResults.setEnabled(true);
        listSearchResults.setListData(Controller.Instance().getAirports().toArray());
    }//GEN-LAST:event_txtDestinationFocusGained

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void txtAirMarshallMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtAirMarshallMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_txtAirMarshallMouseClicked

    private void txtAirMarshallActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAirMarshallActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtAirMarshallActionPerformed

    private void txtAirMarshallFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtAirMarshallFocusGained
        txtAirMarshall.setBorder(BorderFactory.createLineBorder(Color.orange));
        currentField = FieldEditing.AIRMARSHALL;
        listSearchResults.setEnabled(true);
        listSearchResults.setListData(Controller.Instance().getMarshalls().toArray());
    }//GEN-LAST:event_txtAirMarshallFocusGained

    private void txtAirMarshallFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtAirMarshallFocusLost
        txtAirMarshall.setBorder(BorderFactory.createLineBorder(Color.lightGray));
        listSearchResults.setEnabled(false);
    }//GEN-LAST:event_txtAirMarshallFocusLost

    private void txtCopilotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCopilotActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCopilotActionPerformed

    private void ChangePersonal(ArrayList<Staff> staff) {
        this.flight.setOtherPersonal(new HashSet(staff));
        txtPersonal.setText(staff.toString());
        txtPersonal.repaint();
        
    }

    //private void ChangePersonal(ArrayList<Staff> staff) {
    //    this.flight.set(new HashSet(staff));
   //     txtPersonal.setText(staff.toString());
  //      txtPersonal.repaint();
  //  }
    
    private void ChangeStops(ArrayList<Airport> stops) {
        this.flight.setStops(new HashSet<>(stops));
        txtStops.setText(stops.toString());
        txtStops.repaint();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSave;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAir;
    private javax.swing.JLabel lblCopilot;
    private javax.swing.JLabel lblDate;
    private javax.swing.JLabel lblDestination;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblFlightNumber;
    private javax.swing.JLabel lblFrom;
    private javax.swing.JLabel lblOthers;
    private javax.swing.JLabel lblPilot;
    private javax.swing.JLabel lblPlane;
    private javax.swing.JLabel lblStops;
    private javax.swing.JList listSearchResults;
    private javax.swing.JTextField txtAirMarshall;
    private javax.swing.JTextField txtCopilot;
    private javax.swing.JTextField txtDate;
    private javax.swing.JTextField txtDestination;
    private javax.swing.JTextField txtFrom;
    private javax.swing.JTextField txtNumber;
    private javax.swing.JTextField txtPersonal;
    private javax.swing.JTextField txtPilot;
    private javax.swing.JTextField txtPlane;
    private javax.swing.JTextField txtStops;
    // End of variables declaration//GEN-END:variables
}
